<template>
  <div class="login">
    <div class="login_context">
        <div class="login_box">
            <img src="~assets/logo.png" alt="">
        </div>
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="用户名" prop="username">
                <el-input prefix-icon="el-icon-user" v-model="ruleForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input prefix-icon="el-icon-lock" v-model="ruleForm.password"></el-input>
            </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
                <el-button @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
  </div>
</template>

<script>
  export default {
    name: '',
    data(){
        return {
            ruleForm: {
                username: '',
                password: ''
            },
            rules: {
                username: [
                    { required: true, message: '请输用户名', trigger: 'blur' },
                    // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输用户密码', trigger: 'blur' },
                    // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ]
            }   
        }
    },
    methods: {
      submitForm(formName) {
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            const {data:res} = await this.$http.post('login',this.ruleForm);
            console.log(res);

            // 判断请求是否成功
            if(res.meta.status!==200){
                this.$message.error("登录失败")
                return
            }
            // 登录成功后存储token
            this.$message.success("登录成功!")
            window.sessionStorage.setItem('token',res.data.token)
            this.$router.push('/home');
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    }
  }
</script>

<style lang="less" scoped>
.login_context{
    width: 500px;
    height: 400px;
    transform: translate(-50%,-50%);
    position: absolute;
    top: 50%;
    left: 50%;
    border: 1px solid #000;
    text-align: center
}

</style>